package com.ruoyi.common.utils.sms;

import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 短信发送器类
 * 单例模式，待发送的短信先进入队列，使用线程对队列中的短信进行处理
 * @author lxz
 * @since 2015/4/8
 */
public class SMSSender {
    private static Logger logger = LoggerFactory.getLogger(SMSSender.class);
    private static SMSSender smsSender = null;
    private static BlockingQueue<Map<String, String>> queue = new LinkedBlockingQueue<>();

    private SMSSender() {
        pullOutQueue();
    }

    public static SMSSender getInstance() {
        if (smsSender == null) {
            synchronized (SMSSender.class) {
                if (smsSender == null) {
                    smsSender = new SMSSender();
                }
            }
        }
        return smsSender;
    }

    /**
     * 待发送消息放入队列
     * @param map 带发送消息对象
     */
    public void putInQueue(Map<String, String> map) {
        queue.add(map);
    }

    private void pullOutQueue() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    Map<String, String> map = queue.take();
                    if (map.size() > 0) {
                        String params = map.get("params");
                        String mobile = map.get("mobile");
                        String type = map.get("type");
                        String vcode = map.get("vcode");
                        try {
                            if (StringUtils.isNotBlank(mobile)) {
                                logger.info("短信发送开始，手机号[{}]，内容[{}]，[{}]", mobile, params, vcode);
                                //短信验证码
                                if (SendSmsUtils.template_vcode.equals(type)) {
                                    SendSmsUtils.sendVcode(mobile, vcode);
                                } else {
                                    SendSmsUtils.sendNoticeSms(mobile, type, params);
                                }
                                logger.info("短信发送结束，手机号[{}]，内容[{}]，[{}]", mobile, params, vcode);
                            }
                        } catch (Exception exception) {
                            logger.error("短信发送失败，手机号[{}]，内容[{}]，[{}]异常", mobile, params, vcode, exception.getMessage());
                        }
                    }
                } catch (InterruptedException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        });
        thread.start();
    }
}
